use axum::{
    extract::{State, Query},
    http::{Response, StatusCode},
    Json,
};
use tracing::{info, error};

use crate::{
    models::*,
    services::AiService,
};

/// 处理AI聊天请求 - 流式响应
pub async fn chat(
    State(ai_service): State<AiService>,
    Json(req): Json<ChatRequest>,
) -> Response<axum::body::Body> {
    info!("收到AI聊天请求");

    let (tx, rx) = tokio::sync::mpsc::channel::<String>(100);
    
    // 在后台任务中处理API调用
    tokio::spawn(async move {
        let result = ai_service.chat_stream(req, tx).await;
        
        match result {
            Ok(_) => {
                info!("AI聊天流式响应完成");
            }
            Err(e) => {
                error!("AI聊天失败: {:?}", e);
            }
        }
    });
    
    // 创建流式响应
    let stream = ChatStream { inner: rx };
    let body = axum::body::Body::from_stream(stream);
    
    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "text/plain; charset=utf-8")
        .header("Cache-Control", "no-cache")
        .header("Connection", "keep-alive")
        .body(body)
        .unwrap()
}

/// 获取聊天历史
pub async fn get_chat_history(
    State(ai_service): State<AiService>,
    Query(request): Query<HistoryRequest>,
) -> Result<Json<ApiResponse<HistoryResponse>>, StatusCode> {
    info!("获取用户 {} 的聊天历史", request.username);

    let result = ai_service.get_chat_history(request).await;
    
    match result {
        Ok(response) => {
            info!("成功获取聊天历史");
            Ok(Json(response))
        }
        Err(e) => {
            error!("获取聊天历史失败: {:?}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
} 

pub async fn get_message_history(
    State(ai_service): State<AiService>,
    Query(request): Query<MessageHistoryRequest>,
) -> Result<Json<ApiResponse<MessageHistoryResponse>>, StatusCode> {
    info!("获取编号 {} 的消息记录", request.conversation_id);

    let result = ai_service.get_message_history(request).await;

    match result{
        Ok(response) => {
            info!("成功获取消息记录");
            Ok(Json(response))
        }
        Err(e) => {
            error!("获取消息记录失败：{:?}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

pub async fn create_conversation(
    State(ai_service): State<AiService>,
    Query(request): Query<CreateConversationRequest>,
) -> Result<Json<ApiResponse<CreateConversationResponse>>, StatusCode>{
    info!("用户 {} 创建新的对话记录！", request.username);

    let result = ai_service.create_conversation(request).await;

    match result{
        Ok(response) => {
            info!("成功创建对话记录！");
            Ok(Json(response))
        }
        Err(e) => {
            error!("获取对话记录失败：{:?}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}
pub async fn delete_conversations(
    State(ai_service): State<AiService>,
    Query(request): Query<DeleteHistoryRequest>
) -> Result<Json<ApiResponse<DeleteHistoryResponse>>, StatusCode>{
    info!("用户 {} 清空对话记录！", request.username);

    let result = ai_service.delete_conversations(request).await;

    match result{
        Ok(response) => {
            info!("成功清空对话记录！");
            Ok(Json(response))
        }
        Err(e) => {
            error!("清空对话记录失败：{:?}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}



pub async fn create_message(
    State(ai_service): State<AiService>,
    Json(req): Json<CreateMessageRequest>
) -> Result<Json<ApiResponse<CreateMessageResponse>>, StatusCode>{
    info!("向对话 {} 创建新消息记录！", req.conversation_id);

    let result = ai_service.create_message(req).await;

    match result{
        Ok(response) => {
            info!("成功创建消息记录！");
            Ok(Json(response))
        }
        Err(e) => {
            error!("创建消息记录失败：{:?}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}